// 全局变量
let autoRefreshInterval = null;
let chart = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 根据当前页面执行相应的初始化函数
    const path = window.location.pathname;
    const page = path.split("/").pop();
    
    switch(page) {
        case 'index.html':
        case '':
            initHomePage();
            break;
        case 'diagram.html':
            initDiagramPage();
            break;
        case 'metrics.html':
            initMetricsPage();
            break;
        case 'control.html':
            initControlPage();
            break;
    }
});

// 主页初始化
function initHomePage() {
    // 主页特定的初始化代码
    console.log("初始化主页");
}

// 系统示意图页面初始化
function initDiagramPage() {
    // 初始化传感器状态
    updateSensorStatus();
    
    // 为传感器添加点击事件
    const sensors = document.querySelectorAll('.sensor');
    sensors.forEach(sensor => {
        sensor.addEventListener('click', function() {
            const sensorId = this.getAttribute('data-id');
            alert(`传感器 ${sensorId} 被点击。在实际系统中，这里会显示详细数据。`);
        });
    });
}

// 更新传感器状态
function updateSensorStatus() {
    const sensorStatusContainer = document.getElementById('sensor-status');
    
    // 模拟传感器数据
    const sensorData = [
        { id: 1, status: '正常', value: '25.3 MPa' },
        { id: 2, status: '正常', value: '18.7 MPa' },
        { id: 3, status: '警告', value: '42.1 MPa' },
        { id: 4, status: '正常', value: '22.5 MPa' },
        { id: 5, status: '正常', value: '19.8 MPa' },
        { id: 6, status: '正常', value: '21.2 MPa' },
        { id: 7, status: '正常', value: '23.7 MPa' }
    ];
    
    // 清空容器
    sensorStatusContainer.innerHTML = '';
    
    // 生成传感器状态HTML
    sensorData.forEach(sensor => {
        const statusClass = sensor.status === '正常' ? '' : 
                           sensor.status === '警告' ? 'warning' : 'critical';
        
        const sensorElement = document.createElement('div');
        sensorElement.className = 'sensor-status-item';
        sensorElement.innerHTML = `
            <span class="sensor-id">传感器 ${sensor.id}</span>
            <span class="sensor-value ${statusClass}">${sensor.value}</span>
        `;
        
        sensorStatusContainer.appendChild(sensorElement);
    });
}

// 性能指标页面初始化
function initMetricsPage() {
    // 初始化性能指标
    updateMetrics();
    
    // 设置刷新按钮事件
    document.getElementById('refresh-metrics').addEventListener('click', function() {
        updateMetrics();
    });
    
    // 设置自动刷新按钮事件
    document.getElementById('auto-refresh').addEventListener('click', function() {
        toggleAutoRefresh();
    });
    
    // 初始化图表
    initMetricsChart();
}

// 更新性能指标
function updateMetrics() {
    // 模拟性能数据
    const metrics = {
        uptime: randomTime(100, 500) + ' 小时',
        dataCompleteness: randomValue(95, 100, 1) + '%',
        availability: randomValue(98, 100, 1) + '%',
        transferRate: randomValue(50, 100, 0) + ' Mbps',
        dataLatency: randomValue(5, 20, 0) + ' ms',
        packetLoss: randomValue(0, 0.5, 2) + '%',
        accuracy: randomValue(92, 98, 1) + '%',
        responseTime: randomValue(8, 15, 0) + ' 分钟',
        modelUpdate: '每周',
        onlineSensors: randomValue(45, 50, 0),
        sensorLifetime: randomValue(3, 5, 1) + ' 年',
        failureRate: randomValue(0.5, 2, 1) + '%'
    };
    
    // 更新DOM元素
    for (const [key, value] of Object.entries(metrics)) {
        const element = document.getElementById(key);
        if (element) {
            element.textContent = value;
        }
    }
    
    // 更新图表数据
    if (chart) {
        updateChartData();
    }
}

// 初始化性能指标图表
function initMetricsChart() {
    const ctx = document.getElementById('metrics-chart').getContext('2d');
    
    // 生成模拟数据
    const labels = [];
    const data1 = [];
    const data2 = [];
    const data3 = [];
    
    for (let i = 0; i < 24; i++) {
        labels.push(`${i}:00`);
        data1.push(randomValue(20, 40, 1));
        data2.push(randomValue(50, 80, 1));
        data3.push(randomValue(0.1, 2, 2));
    }
    
    chart = new Chart(ctx, {
        type: 'line',
        data: {
            labels: labels,
            datasets: [
                {
                    label: '平均应力 (MPa)',
                    data: data1,
                    borderColor: '#1a6bc4',
                    backgroundColor: 'rgba(26, 107, 196, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: '数据传输速率 (Mbps)',
                    data: data2,
                    borderColor: '#4CAF50',
                    backgroundColor: 'rgba(76, 175, 80, 0.1)',
                    tension: 0.4,
                    fill: true
                },
                {
                    label: '丢包率 (%)',
                    data: data3,
                    borderColor: '#FF9800',
                    backgroundColor: 'rgba(255, 152, 0, 0.1)',
                    tension: 0.4,
                    fill: true
                }
            ]
        },
        options: {
            responsive: true,
            plugins: {
                title: {
                    display: true,
                    text: '24小时性能趋势'
                }
            },
            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });
}

// 更新图表数据
function updateChartData() {
    if (!chart) return;
    
    chart.data.datasets.forEach(dataset => {
        dataset.data = dataset.data.map(() => {
            if (dataset.label.includes('应力')) {
                return randomValue(20, 40, 1);
            } else if (dataset.label.includes('速率')) {
                return randomValue(50, 80, 1);
            } else {
                return randomValue(0.1, 2, 2);
            }
        });
    });
    
    chart.update();
}

// 切换自动刷新
function toggleAutoRefresh() {
    const button = document.getElementById('auto-refresh');
    const status = document.getElementById('auto-refresh-status');
    
    if (autoRefreshInterval) {
        clearInterval(autoRefreshInterval);
        autoRefreshInterval = null;
        status.textContent = '关';
        button.classList.remove('btn-primary');
        button.classList.add('btn-secondary');
    } else {
        autoRefreshInterval = setInterval(updateMetrics, 5000);
        status.textContent = '开';
        button.classList.remove('btn-secondary');
        button.classList.add('btn-primary');
    }
}

// 控制面板页面初始化
function initControlPage() {
    // 初始化仪表盘
    initGauges();
    
    // 设置控制按钮事件
    setupControlButtons();
    
    // 设置预警处理按钮事件
    setupAlertButtons();
    
    // 开始实时数据更新
    startRealTimeUpdates();
}

// 初始化仪表盘
function initGauges() {
    updateGauge('stress-gauge', 'stress-value', 65, 100, '#4CAF50', '#FF9800', '#F44336');
    updateGauge('displacement-gauge', 'displacement-value', 12, 30, '#4CAF50', '#FF9800', '#F44336');
    updateGauge('vibration-gauge', 'vibration-value', 3.5, 10, '#4CAF50', '#FF9800', '#F44336');
    updateGauge('temperature-gauge', 'temperature-value', 22, 50, '#4CAF50', '#FF9800', '#F44336');
}

// 更新仪表盘
function updateGauge(canvasId, valueId, value, maxValue, lowColor, mediumColor, highColor) {
    const canvas = document.getElementById(canvasId);
    const ctx = canvas.getContext('2d');
    const valueElement = document.getElementById(valueId);
    
    // 清除画布
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 计算角度
    const angle = (value / maxValue) * Math.PI;
    const startAngle = Math.PI;
    const endAngle = startAngle + angle;
    
    // 绘制背景弧
    ctx.beginPath();
    ctx.arc(canvas.width / 2, canvas.height - 10, canvas.width / 2 - 10, Math.PI, 2 * Math.PI);
    ctx.strokeStyle = '#eee';
    ctx.lineWidth = 15;
    ctx.stroke();
    
    // 确定颜色
    let color = lowColor;
    if (value > maxValue * 0.7) {
        color = highColor;
    } else if (value > maxValue * 0.4) {
        color = mediumColor;
    }
    
    // 绘制值弧
    ctx.beginPath();
    ctx.arc(canvas.width / 2, canvas.height - 10, canvas.width / 2 - 10, startAngle, endAngle);
    ctx.strokeStyle = color;
    ctx.lineWidth = 15;
    ctx.stroke();
    
    // 更新数值显示
    valueElement.textContent = value;
}

// 设置控制按钮事件
function setupControlButtons() {
    // 数据采集控制
    document.getElementById('start-collection').addEventListener('click', function() {
        showNotification('数据采集已启动', 'success');
    });
    
    document.getElementById('stop-collection').addEventListener('click', function() {
        showNotification('数据采集已停止', 'warning');
    });
    
    document.getElementById('adjust-frequency').addEventListener('click', function() {
        const frequency = prompt('请输入新的采集频率 (Hz):', '10');
        if (frequency) {
            showNotification(`采集频率已调整为 ${frequency} Hz`, 'info');
        }
    });
    
    // AI分析控制
    document.getElementById('start-analysis').addEventListener('click', function() {
        showNotification('AI分析引擎已启动', 'success');
    });
    
    document.getElementById('stop-analysis').addEventListener('click', function() {
        showNotification('AI分析引擎已停止', 'warning');
    });
    
    document.getElementById('update-model').addEventListener('click', function() {
        showNotification('AI模型更新已开始，预计需要5分钟', 'info');
    });
    
    // 预警系统控制
    document.getElementById('enable-alerts').addEventListener('click', function() {
        showNotification('预警系统已启用', 'success');
    });
    
    document.getElementById('disable-alerts').addEventListener('click', function() {
        showNotification('预警系统已禁用', 'warning');
    });
    
    document.getElementById('test-alert').addEventListener('click', function() {
        showNotification('测试预警已发送', 'info');
    });
    
    // 系统维护
    document.getElementById('backup-data').addEventListener('click', function() {
        showNotification('数据备份已开始', 'info');
    });
    
    document.getElementById('system-check').addEventListener('click', function() {
        showNotification('系统检查已完成，未发现问题', 'success');
    });
    
    document.getElementById('export-report').addEventListener('click', function() {
        showNotification('报告导出已开始', 'info');
    });
}

// 设置预警处理按钮事件
function setupAlertButtons() {
    const alertButtons = document.querySelectorAll('.alert-action');
    alertButtons.forEach(button => {
        button.addEventListener('click', function() {
            const alertItem = this.closest('.alert-item');
            const alertTitle = alertItem.querySelector('h4').textContent;
            
            showNotification(`已处理预警: ${alertTitle}`, 'success');
            
            // 在实际系统中，这里会向服务器发送处理请求
            // 模拟处理成功，移除预警项
            alertItem.style.opacity = '0.5';
            this.textContent = '已处理';
            this.disabled = true;
        });
    });
}

// 开始实时数据更新
function startRealTimeUpdates() {
    // 每3秒更新一次仪表盘数据
    setInterval(() => {
        updateGauge('stress-gauge', 'stress-value', randomValue(20, 80, 1), 100, '#4CAF50', '#FF9800', '#F44336');
        updateGauge('displacement-gauge', 'displacement-value', randomValue(5, 25, 1), 30, '#4CAF50', '#FF9800', '#F44336');
        updateGauge('vibration-gauge', 'vibration-value', randomValue(2, 8, 1), 10, '#4CAF50', '#FF9800', '#F44336');
        updateGauge('temperature-gauge', 'temperature-value', randomValue(15, 35, 1), 50, '#4CAF50', '#FF9800', '#F44336');
    }, 3000);
}

// 显示通知
function showNotification(message, type) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 15px 20px;
        border-radius: 5px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        animation: slideIn 0.3s ease;
    `;
    
    // 根据类型设置背景色
    if (type === 'success') {
        notification.style.backgroundColor = '#4CAF50';
    } else if (type === 'warning') {
        notification.style.backgroundColor = '#FF9800';
    } else if (type === 'info') {
        notification.style.backgroundColor = '#2196F3';
    } else {
        notification.style.backgroundColor = '#666';
    }
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 3秒后移除
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

// 添加通知动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
`;
document.head.appendChild(style);

// 工具函数：生成随机数值
function randomValue(min, max, decimals = 0) {
    const value = Math.random() * (max - min) + min;
    return Number(value.toFixed(decimals));
}

// 工具函数：生成随机时间
function randomTime(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}